package com.example.demo.controller;

import com.example.demo.polo.MyUser;
import com.example.demo.service.WebSocketService;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpSession;
import java.util.ArrayList;
import java.util.List;
import java.util.Map;


/**
 * @Auther: Graycat
 * @Date: 2020/7/20 13:14
 * Create by lwj.
 */

@Controller
public class WebSocketController {

//    @Autowired
//    private RoomRepository repository;

    private String userId = "test";
    private int roomId = -1;

    @RequestMapping("/index")
    public String getIndex() {
        return "index";
    }

    @RequestMapping("/toChatRoom")
    public String toChatRoom() {
        return "chatroomIndex";
    }

    @RequestMapping("/login")
    public String getLogin() {
        return "login";
    }

    @RequestMapping("/api/setId")
    @ResponseBody
    public void setId( @RequestParam(value = "roomId") String roomId,@RequestParam(value = "userId")String userId ){
        WebSocketService.userInRoom.put(userId,roomId);
    }

    @RequestMapping("/check")
    public String checkLogin(HttpServletRequest request, String userId, int roomId) {
        System.out.println( userId+"  "+roomId);
        //检查密码账号正确性
        this.roomId = roomId;
        this.userId = userId;
        HttpSession session = request.getSession();
        session.setAttribute("userId",userId);
        return "chatroomIndex";
    }

    @RequestMapping("/api/getId")
    @ResponseBody
    public String getSid(){
        String result = "{\"userId\":"+userId+",\"roomId\":"+roomId+"}";
        return result;
    }

    @RequestMapping("api/getOnlineUser")
    @ResponseBody
    public List<String> getOnlineUser( String roomId ){
        List<String> userList = new ArrayList<>();
        for ( Map.Entry<String,String> userItem: WebSocketService.userInRoom.entrySet() ){
            if( userItem.getValue().equals(roomId) ){
                userList.add(userItem.getKey());
            }
        }
        return userList;
    }

    @RequestMapping("/api/getRoomId")
    @ResponseBody
    public int getRoomId(){
        return roomId;
    }

    @RequestMapping("/api/getUserId")
    @ResponseBody
    public String getUserId(){
        return userId;
    }
}


